import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lz_app_core/constants/app_manager.dart';
import 'package:lz_app_core/enum/app_enum.dart';
import 'package:lz_app_core/extension/kd_empty_extension.dart';
import 'package:lz_app_core/kd_user/kd_user_info.dart';
import 'package:lz_base/kd_base.dart';
import 'package:lz_login/kd_login.dart';
import 'package:lz_login/src/core/kd_mine_title_minix.dart';
import 'package:lz_login/src/serve/kd_login_api.dart';
import 'package:lz_login/src/serve/models/kd_mine_info_detail_model.dart';
import 'package:lz_router/kd_router.dart';
import 'package:lz_ui/kd_ui.dart';
import '../core/kd_login_config.dart';
import '../serve/models/kd_mine_item.dart';

class MyWidget extends StatefulWidget with KDRouterObserverType {
  MyWidget({super.key});

  late _MyWidgetState _temp;

  @override
  // ignore: no_logic_in_create_state
  State<MyWidget> createState() {
    _temp = _MyWidgetState();
    return _temp;
  }

  /// router
  @override
  String get routerName => CommonRouterName.tabbar.routerName;

  @override
  viewWillAppear() {
    _temp.loadData();
  }
}

class _MyWidgetState extends State<MyWidget> with KDMineTitleMinix {
  RxInt _msgCount = 0.obs;
  KDInfoDetailModel? _inofModel;

  @override
  void initState() {
    loadData();

    super.initState();
  }

  String get _name => _inofModel?.userName ?? KDUser.info.name ?? "";
  String get _phone => _inofModel?.memberPhone ?? KDUser.info.phone ?? "";
  String get _level =>
      _inofModel?.memberLevel ??
      KDUser.info.memberRoleRelation?.memberLevel ??
      "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor:Colors.white,
        body: CustomScrollView(
      shrinkWrap: true,
      slivers: [
        SliverPadding(
          padding: EdgeInsets.only(),
          sliver:
          SliverList(
              delegate: SliverChildListDelegate([
                Stack(children: [
                  _HeadUserInfo(_name, _level, _phone),
                  // _topButtonView(),
                  Container(
                    height: 46,
                    width: KD.screenW,
                    margin: EdgeInsets.only(
                        left: 0.0, top: 128.0 + KD.statusBarHeight, right: 0.0, bottom: 0),
                    padding: EdgeInsets.only(left: 15, top: 15),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.vertical(
                          top: Radius.circular(10.dp)),
                      color: Colors.white,
                      boxShadow: [
                        BoxShadow(
                            color: Colors.black.withOpacity(0.03),
                            offset: const Offset(0, 6),
                            blurRadius: 4.0,
                            spreadRadius: 0.0)
                      ],
                    ),
                    child: Text('服务中心',
                      textAlign: TextAlign.left,
                      style: TextStyle(
                        fontSize: KD.font2(16),
                        color: KDColor.text_black,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ]),
                _bottomButtonView()
              ])),
        ),
      ],
    ));
  }

  Widget _HeadUserInfo(String name, String level, String phoneNum) {
    return Container(
      constraints: BoxConstraints.expand(height: (140.0 + KD.statusBarHeight)),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('images/wode_header_bg.png'),
          fit: BoxFit.cover, // 可以调整图片大小适应容器
        ),
      ),
      child: Padding(
        padding: EdgeInsets.only(top: 32.0 + KD.statusBarHeight),
        child: Align(
          alignment: Alignment.topCenter,
          child: Container(
            constraints: const BoxConstraints.expand(height: 62.0),
            padding: const EdgeInsets.only(left: 16.0, right: 0),
            height: 62,
            child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  InkWell(
                    child: Container(
                        width: 60.0,
                        height: 60.0,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(30.0),
                          color: Colors.white,
                          border: Border.all(width: 2.dp, color: Colors.white),
                        ),
                        child: KDIsEmpty.stringEmpty(KDUser.info.avatar)
                            ? const Image(
                                image: AssetImage('images/icon_avart.png'))
                            : Container(
                                width: 58.0,
                                height: 58.0,
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(29.0),
                                ),
                                child: NetworkImageWidget(
                                  url: KDUser.info.avatar!,
                                ),
                              )),
                    onTap: () {
                      KDRouter.to(KDLoginRouter.mineInfo)
                          ?.then((value) => loadData());
                    },
                  ),
                  Expanded(
                      child: Padding(
                    padding: const EdgeInsets.only(left: 12.0),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                            crossAxisAlignment: CrossAxisAlignment.center,
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Container(
                                constraints: BoxConstraints(maxWidth: nameMaxWidth),
                                child: Text(
                                  name,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                      fontSize: AppManager.isOwner ? 16 : 18,
                                      color: Colors.white,
                                      fontWeight: FontWeight.w600),
                                  textAlign: TextAlign.left,
                                ),
                              ),
                              // level.isEmpty
                              //     ? Container()
                              //     : Container(
                              //         width: 42.0,
                              //         height: 22.0,
                              //         margin: const EdgeInsets.only(left: 4.0),
                              //         decoration: BoxDecoration(
                              //             borderRadius:
                              //                 BorderRadius.circular(11.0),
                              //             color: const Color(0xFF1D2129)),
                              //         child: Center(
                              //             child: Text(level,
                              //                 style: const TextStyle(
                              //                     fontSize: 16,
                              //                     color: Colors.white),
                              //                 textAlign: TextAlign.center))),
                            ]),
                        Text(
                          phoneNum,
                          style:
                              TextStyle(fontSize: 16.0, color: Colors.white),
                          textAlign: TextAlign.left,
                        )
                      ],
                    ),
                  )),
                  SizedBox(
                    width: 12.kdw,
                  ),
                  KDUserPermissionWidget(
                    type: KDUserPermissionType.mine_to_auth,
                    child: _goCertification(),
                  ),
                ]),
          ),
        ),
      ),
    );
  }

  Widget _goCertification() {
    if (_inofModel == null) return Container();
    return InkWell(
        onTap: () {
          KDRouter.to(KDLoginRouter.certificationList)
              ?.then((value) => loadData());
        },
        child:
        Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(topLeft: Radius.circular(50),
                  bottomLeft: Radius.circular(50)),
              color: Colors.white,
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                    width: 70.0,
                    height: 34.0,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.horizontal(left: Radius.circular(17),right: Radius.zero),
                      color: Colors.transparent,
                    ),
                    child: Center(
                        child: Text(
                          (_inofModel?.showGoCertificate ?? false)
                              ? '   去认证'
                              : "  认证信息",
                          style: TextStyle(
                              fontSize: 12.fs, color: KDColor.text_blue,
                              fontWeight: FontWeight.w600),
                          textAlign: TextAlign.center,
                        ))),
                const SizedBox(width: 4),
                Icon(
                  KDIcon.zhankai1,
                  color: KDColor.main,
                  size: 16,
                ),
              ],
            )
        ),
        );
  }

  Widget _topButtonView() {
    return Container(
      margin: EdgeInsets.only(
          left: 0.0, top: 130.0 + KD.statusBarHeight, right: 0.0),
      height: 104.0,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.only(topLeft: Radius.circular(12), topRight: Radius.circular(12)),
        color: Colors.white,
        boxShadow: [
          // _shadow(),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          KDUserPermissionWidget(
              //我的司机
              type: KDUserPermissionType.mine_driver,
              child: Expanded(
                  flex: 1,
                  child: _getButton(
                      AppManager.appName.isShipTransport
                          ? 'wode_chuanzhang_icon'
                          : 'wode_siji_icon',
                      getMyDriverTitle(), () {
                    KDRouter.to('/myDriverPage');
                  }))),
          KDUserPermissionWidget(
            //我的货主
            type: KDUserPermissionType.mine_owner,
            // permission: "mine:owner",
            child: Expanded(
                flex: 1,
                child: _getButton('wode_huozhu_icon', getMineOwnerTitle(), () {
                  KDRouter.to('/myOwnerPage');
                })),
          ),
          KDUserPermissionWidget(
            type: KDUserPermissionType.mine_car,
            child: Expanded(
                flex: 1,
                child: _getButton('wode_cheliang_icon', getWoDeCheLiang1Title(),
                    () {
                  KDRouter.to('/myCarPage');
                })),
          ),
          KDUserPermissionWidget(
            // permission: "mine:driver:boss",
            type: KDUserPermissionType.mine_driver_boss,
            child: Expanded(
                flex: 1,
                child: _getButton(
                    AppManager.appName.isShipTransport
                        ? 'wode_diaoduyuan_icon'
                        : 'wode_diaoduyuan_icon',
                    getWoDeCheDuiChangTitle(), () {
                  KDRouter.to('/myCaptainPage');
                })),
          ),
        ],
      ),
    );
  }

  BoxShadow _shadow() {
    return BoxShadow(
        color: Colors.black.withOpacity(0.05),
        offset: const Offset(0, 0.5),
        blurRadius: 5.0,
        spreadRadius: 2.0);
  }

  bool get showReceipt => AppManager.appName.isOwner;

  String getWalletRouterName() {
    // if (AppManager.appName == AppName.kdOwner) {
    //   return '/myWalletPage';
    // } else {
      return "/myBankChannelTypePage";
    // }
  }

  List<KDMineItem?> _bottomBtnList() {
    List<KDMineItem?> list = [
      KDUserPermission.checkType(KDUserPermissionType.mine_car)
          ? KDMineItem(
        imageName: 'wodecheliang',
        title: "我的车辆",
        routerName: '/myCarPage',
      )
          : null,
      KDUserPermission.checkType(KDUserPermissionType.mine_driver_boss)
          ? KDMineItem(
        imageName: 'wodediaoduyuan',
        title: "我的调度员",
        routerName:'/myCaptainPage',
      )
          : null,
      KDUserPermission.checkType(KDUserPermissionType.mine_driver)
          ? KDMineItem(
        imageName: 'wodesiji',
        title: "我的司机",
        routerName: '/myDriverPage',
      )
          : null,
      KDUserPermission.checkType(KDUserPermissionType.mine_owner)
          ? KDMineItem(
        imageName: 'wodehuozhu',
        title: "我的货主",
        routerName: '/myOwnerPage',
      )
          : null,
      KDUserPermission.checkType(KDUserPermissionType.mine_wallet)
          ? KDMineItem(
              imageName: 'wodeqianbao',
              title: "我的钱包",
              routerName: getWalletRouterName(),
            )
          : null,
      // KDUserPermission.checkType(KDUserPermissionType.invite_driver)
      //     ? KDMineItem(
      //         imageName: KDIcon.yaoqingzhuce,
      //         title: "邀请司机注册",
      //         routerName: '/contractsListPage',
      //       )
      //     : null,
      KDUserPermission.checkType(KDUserPermissionType.mine_project)
          ? KDMineItem(
              imageName: 'wodexiangmu',
              title: "我的项目",
              routerName: '/proManagePage',
            )
          : null,
      KDUserPermission.checkType(KDUserPermissionType.mine_broker)
          ? KDMineItem(
              imageName: 'wodejingjiren',
              title: "我的经纪人",
              routerName: '/myBrokerPage',
            )
          : null,
      if (AppManager.appName.isBroker &&
          KDUserPermission.checkType(KDUserPermissionType.mine_statistics))
        KDMineItem(
          imageName: 'tongji',
          title: "统计",
          routerName: '/statistic',
        ),
      KDUserPermission.checkType(KDUserPermissionType.mine_contract)
          ? KDMineItem(
              imageName: 'wodehetong',
              title: "我的合同",
              routerName: '/contractsListPage',
            )
          : null,
      KDUserPermission.checkType(KDUserPermissionType.mine_address)
          ? KDMineItem(
              imageName: 'wodedizhi', //wodedizhi
              title: "我的地址",
              routerName: '/myAddressPage',
            )
          : null,
      KDUserPermission.checkType(KDUserPermissionType.mine_line)
          ? KDMineItem(
              imageName: 'wodeluxian', //wodeluxian
              title: "我的路线",
              routerName: '/myWayPage',
            )
          : null,
      if (KDUserPermission.checkType(
              KDUserPermissionType.mine_billing_address) &&
          AppManager.appName.isOwner)
        KDMineItem(
          imageName: 'wodeshoupiaodizhi', //wodeluxian
          title: "我的收票地址",
          routerName: '/myReceiptPage',
        ),
      // KDUserPermission.checkType(KDUserPermissionType.mine_setting)
      //     ?
      KDMineItem(
              imageName: 'shezhi',
              title: "设置",
              routerName: KDLoginRouter.setting,
            )
          // : null,
    ];
    return list;
  }

  Widget _bottomButtonView() {
    List<KDMineItem?> list = _bottomBtnList();

    List<KDMineItem> itemList = [];
    for (var e in list) {
      if (e != null) {
        itemList.add(e);
      }
    }

// 210.0 + KD.statusBarHeight
    return Container(
        margin: EdgeInsets.only(
            left: 0.0, top: 0, right: 0.0, bottom: KD.bottomSpace),
        padding: EdgeInsets.zero,
        // height: 184.0,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(0.0),
            color: Colors.white,
            // boxShadow: [
            //   BoxShadow(
            //       color: Colors.black.withOpacity(0.03),
            //       offset: const Offset(0, 6),
            //       blurRadius: 4.0,
            //       spreadRadius: 0.0)
            // ],
        ),
        child:
        GridView.builder(
        padding: EdgeInsets.zero,
          shrinkWrap: true,
          physics: const ScrollPhysics(),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4, // 每行显示的列数
            crossAxisSpacing: 0.0, // 列之间的水平间距
            mainAxisSpacing: 0.0,
          ),
          itemCount: itemList.length, // 子项的总数
          itemBuilder: (BuildContext context, int index) {
            var item = itemList[index];
            return _getGridItem(
              assetImageName: item.imageName,
              title: item.title,
              func: () {
                KDRouter.to(item.routerName);
              },
            );
          },
        ),

        // GridView.count(
        //   padding: EdgeInsets.zero,
        //   shrinkWrap: true,
        //   physics: const ScrollPhysics(),
        //   crossAxisCount: 4,
        //   children: List.generate(itemList.length, (index) {
        //     var item = itemList[index];
        //     return _getGridItem(
        //       assetImageName: item.iconData,
        //       title: 'item.title',
        //       func: () {
        //         KDRouter.to(item.routerName);
        //       },
        //     );
        //   }),
        // ),

    );
  }

  Widget _getGridItem(
      {required String assetImageName, required String title, Function()? func}) {
    Widget badgeWidget = (_msgCount.value == 0)
        ? const SizedBox()
        : Container(
      margin: const EdgeInsets.only(left: 8.0),
      width: 18.0,
      height: 18.0,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0), color: Colors.red),
      child: Center(
        child: Text('${_msgCount.value%100}',
            style: const TextStyle(fontSize: 12, color: Colors.white)),
      ),
    );

    return InkWell(
      onTap: func,
      child: SizedBox(
        height: 88,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Padding(
              padding: EdgeInsets.only(top: 15.0),
              child:
              Stack(
                  children: [
                    Image(
                      image: AssetImage('images/${assetImageName}.png',
                          package: KDLoginConfig.package),
                      height: KD.sizeH(35),
                      width: KD.sizeW(35),
                    ),
                    Positioned(
                      top: 0,
                      right: 0,
                      child:
                      badgeWidget,
                    )
                  ]
              ),
            ),
            Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(top: 0.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(title,
                          style: TextStyle(fontSize: 14.0, color: KDColor.text_black, fontWeight: FontWeight.w400,),
                          textAlign: TextAlign.center,),
                    ],
                  ),
                )),
          ],
        ),
      ),
    );
  }

  Widget _getListItem(
      {required IconData iconData, required String title, Function()? func}) {
    Widget badgeWidget = (_msgCount.value == 0)
        ? const SizedBox()
        : Container(
            margin: const EdgeInsets.only(left: 8.0),
            width: 20.0,
            height: 20.0,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.0), color: Colors.red),
            child: Center(
              child: Text('${_msgCount.value}',
                  style: const TextStyle(fontSize: 12, color: Colors.white)),
            ),
          );

    return InkWell(
      onTap: func,
      child: SizedBox(
        height: 56,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Padding(
                padding: const EdgeInsets.only(left: 16.0),
                child: Icon(
                  iconData,
                  color: KDColor.title,
                )),
            Expanded(
                child: Padding(
              padding: const EdgeInsets.only(left: 8.0),
              child: Row(
                children: [
                  Text(title,
                      style: TextStyle(fontSize: 16.0, color: KDColor.title)),
                  badgeWidget
                ],
              ),
            )),
            Padding(
                padding: const EdgeInsets.only(right: 16.0),
                child: Icon(Icons.arrow_forward_ios_outlined,
                    color: KDColor.title, size: 16.0))
          ],
        ),
      ),
    );
  }

  Widget _getButton(String assetImageName, String title, Function()? func) {
    return InkWell(
        onTap: func,
        child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Image(
                image: AssetImage('images/${assetImageName}.png',package: KDLoginConfig.package),
                height: KD.sizeH(40),
                width: KD.sizeW(40),
              ),
              const SizedBox(height: 5.0),
              Text(title, style: TextStyle(fontSize: 14, color: KDColor.text_black,fontWeight: FontWeight.w500),)
            ]));
  }

  loadData() async {
    KDInfoDetailModel? inofModel = await KDLoginApi.mineDetailInfo();
    if (inofModel == null) return;
    if (inofModel.memberLevel != null && inofModel.memberLevel!.contains("0")) {
      inofModel.memberLevel = inofModel.memberLevel!.replaceFirst("0", "V");
    }

    if (inofModel.memberAuthInfoVOList != null) {
      for (var item in inofModel.memberAuthInfoVOList!) {
        String authType = item.authType ?? "0";
        if (["01", "06"].contains(authType)) continue;

        KDCertificationStateType type =
            KDCertificationStateType.from(int.parse(item.authStatus ?? "0"));
        inofModel.showGoCertificate = type.editing();
        if (inofModel.showGoCertificate) break;
      }
    }

    setState(() {
      _inofModel = inofModel;
    });
  }

  double get nameMaxWidth => (KDUserPermission.check(KDUserPermissionType.mine_to_auth.permission) ? KD.screenW/2 : KD.screenW/2) - 20;
}
